package cn.aran.basic.service.impl;

import cn.aran.basic.constants.BaseConstants;
import cn.aran.basic.exception.BusinessException;
import cn.aran.basic.jwt.JwtUtils;
import cn.aran.basic.jwt.RsaUtils;
import cn.aran.basic.jwt.Userinfo;
import cn.aran.basic.service.ILoginService;
import cn.aran.basic.utils.*;
import cn.aran.basic.vo.LoginVo;
import cn.aran.basic.vo.WechatVo;
import cn.aran.sys.domain.Menu;
import cn.aran.sys.mapper.MenuMapper;
import cn.aran.sys.mapper.PermissionMapper;
import cn.aran.user.domain.Logininfo;
import cn.aran.user.domain.User;
import cn.aran.user.domain.Wxuser;
import cn.aran.user.mapper.LogininfoMapper;
import cn.aran.user.mapper.UserMapper;
import cn.aran.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPri;
    /**
    * @Title: accountLogin
    * @Description: 无状态token登录
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/14 16:02
    * @Parameters: [loginVo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    /* @Override
    public Map<String, Object> accountLogin(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        Integer type = loginVo.getType();
        // 参数为空校验
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("必要参数为空!");
        }
        // 根据username和type判断密码是否正确
        Logininfo logininfo = logininfoMapper.loadByAccount(username, type);
        // 判断账户是否存在
        if (logininfo == null){
            throw new BusinessException("账号或密码错误,请重新输入!");
        }
        // 判断账户是否激活
        if (!logininfo.getDisable()){
            throw new BusinessException("账户未激活!请激活账户!");
        }
        // 对password进行加盐加密
        String saltPasswordTemp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        // 判断密码是否正确
        if (!logininfo.getPassword().equals(saltPasswordTemp)){
            throw new BusinessException("账号或密码错误,请重新输入!");
        }
        // 生成token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 重置敏感信息
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 将token和logininfo返回
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;

    } */

    /**
    * @Title: accountLogin
    * @Description: jwt登录
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/14 16:04
    * @Parameters: [loginVo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> accountLogin(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        Integer type = loginVo.getType();
        // 参数为空校验
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("必要参数为空!");
        }
        // 根据username和type判断密码是否正确
        Logininfo logininfo = logininfoMapper.loadByAccount(username, type);
        // 判断账户是否存在
        if (logininfo == null){
            throw new BusinessException("账号或密码错误,请重新输入!");
        }
        // 判断账户是否激活
        if (!logininfo.getDisable()){
            throw new BusinessException("账户未激活!请激活账户!");
        }
        // 对password进行加盐加密
        String saltPasswordTemp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        // 判断密码是否正确
        if (!logininfo.getPassword().equals(saltPasswordTemp)){
            throw new BusinessException("账号或密码错误,请重新输入!");
        }
        return loginSuccessJwtHandler(logininfo);

    }

    /**
    * @Title: loginSuccessJwtHandler
    * @Description: jwt加密工具类
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/14 18:42
    * @Parameters: [logininfo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        // 创建Usernifo
        Userinfo userinfo = new Userinfo();
        userinfo.setLogininfo(logininfo);
        // 将token和logininfo返回
        Map<String, Object> map = new HashMap<>();
        if (logininfo.getType() == 0){
            // 登录用户的权限
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininfoId(logininfo.getId());
            // 登录用户的菜单
            List<Menu> menus = menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            userinfo.setPermissions(permissions);
            userinfo.setMenus(menus);
            map.put("permissions",permissions);
            map.put("menus",menus);
        }
        // 生成token
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPri).getFile());
        String token = JwtUtils.generateTokenExpireInMinutes(userinfo, privateKey, 1440);
        // 重置敏感信息
        logininfo.setSalt("");
        logininfo.setPassword("");
        map.put("token",token);
        map.put("logininfo", logininfo);
        return map;
    }

    /**
    * @Title: loginCode
    * @Description: 短信验证码登陆
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/14 16:00
    * @Parameters: [loginVo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> loginCode(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String loginCode = loginVo.getLoginCode();
        Integer type = loginVo.getType();
        // 参数为空校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(loginCode)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("必要参数为空!");
        }
        // 根据username和type判断密码是否正确
        Logininfo logininfo = logininfoMapper.loadByPhone(phone, type);
        // 判断账户是否存在
        if (logininfo == null){
            throw new BusinessException("请先注册!");
        }
        // 判断账户是否激活
        if (!logininfo.getDisable()){
            throw new BusinessException("账户未激活!请激活账户!");
        }
        // 判断验证码是否存在
        String loginCodeKey = BaseConstants.VerifyCodeConstant.PHONE_LOGIN_PREFIX + phone;
        Object loginCodeRedis = redisTemplate.opsForValue().get(loginCodeKey);
        if (loginCodeRedis == null){
            throw new BusinessException("验证码已过期,请重新获取!");
        }
        // 判断验证码是否一致
        String[] loginCodeRedises = loginCodeRedis.toString().split(":");
        if (!loginCodeRedises[0].equalsIgnoreCase(loginCode)){
            throw new BusinessException("验证码错误,请重新输入!");
        }
        // 生成token
        // String token = UUID.randomUUID().toString();
        // redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // // 重置敏感信息
        // logininfo.setSalt("");
        // logininfo.setPassword("");
        // // 将token和logininfo返回
        // Map<String, Object> map = new HashMap<>();
        // map.put("token",token);
        // map.put("logininfo",logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }


    /**
    * @Title: wechat
    * @Description: 微信登录
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/10 17:20
    * @Parameters: [weChatVo]
    * @Return cn.aran.basic.utils.AjaxResult
    */
    @Override
    public AjaxResult wechat(WechatVo wechatVo) {
        String code = wechatVo.getCode();
        // 非空校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数为空!");
        }
        // 拼接请求地址
        String url = BaseConstants.WechatConstant.TOKEN_URL
                .replace("APPID",BaseConstants.WechatConstant.APPID)
                .replace("SECRET",BaseConstants.WechatConstant.SECRET)
                .replace("CODE",code);
        // 发送请求
        String jsonStr = HttpClientUtils.httpGet(url);
        // 获取到access_token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        // 根据openId查询
        Wxuser wxuser = wxuserMapper.loadByOpenid(openId);
        // 判断wxuser是否存在
        if (wxuser != null && wxuser.getUserId() != null){ // 存在
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 生成token
            // String token = UUID.randomUUID().toString();
            // redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            // // 重置敏感信息
            // logininfo.setSalt("");
            // logininfo.setPassword("");
            // // 将token和logininfo返回
            // Map<String, Object> map = new HashMap<>();
            // map.put("token",token);
            // map.put("logininfo",logininfo);
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        // 不存在,传递access_token和openid到绑定页面,进行绑定
        StringBuffer bindStr = new StringBuffer()
                .append("?accessToken=")
                .append(access_token)
                .append("&openId=")
                .append(openId);
        return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(bindStr);
    }

    /**
    * @Title: binder
    * @Description: 微信绑定
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/10 20:14
    * @Parameters: [weChatVo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> binder(WechatVo wechatVo) {
        String phone = wechatVo.getPhone();
        String verifyCode = wechatVo.getVerifyCode();
        String accessToken = wechatVo.getAccessToken();
        String openId = wechatVo.getOpenId();
        // 非空校验
        if (StringUtils.isEmpty(phone)
            || StringUtils.isEmpty(verifyCode)
            || StringUtils.isEmpty(accessToken)
            || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数为空!");
        }
        // 判断验证码是否存在
        String binderCodeKey = BaseConstants.VerifyCodeConstant.WECHAT_BINDER_PREFIX + phone;
        Object binderCodeRedis = redisTemplate.opsForValue().get(binderCodeKey);
        if (binderCodeRedis == null){
            throw new BusinessException("验证码已过期,请重新获取!");
        }
        // 判断验证码是否一致
        String[] binderCodeRedises = binderCodeRedis.toString().split(":");
        if (!binderCodeRedises[0].equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码错误,请重新输入!");
        }
        // 判断账户是否存在
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if (user == null){
            user = wechatVo2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        // 通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 生成token
        // String token = UUID.randomUUID().toString();
        // redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // // 重置敏感信息
        // logininfo.setSalt("");
        // logininfo.setPassword("");
        // // 将token和logininfo返回
        // Map<String, Object> map = new HashMap<>();
        // map.put("token",token);
        // map.put("logininfo",logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    /**
    * @Title: logout
    * @Description: 退出
    * @Author: Aran
    * @Version: 1.0
    * @Date:  2022/7/12 15:14
    * @Parameters: [token]
    * @Return void
    */
    @Override
    public void logout(String token) {
        // redisTemplate.delete(token);
        System.out.println("退出了");
    }


    private User wechatVo2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String initPwd = "1";
        // SendSmsUtil.sendMsg(initPwd);
        String saltPassword = MD5Utils.encrypByMd5(salt + initPwd);
        user.setPassword(saltPassword);
        user.setSalt(salt);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
